package com.cskaoyan.gateway.controller.shopping;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.annotation.Anoymous;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 购物车相关接口
 * 购物车的存储使用redis
 * 存储格式为map<Long,List<AddCartBO>>
 * Long为当前用户的id
 *
 * @author ZhangXiao on 2021/7/20
 */
@RestController
@RequestMapping("shopping")
public class ShoppingCartsController {

    @Reference(timeout = 3000, check = false)
    ICartService iCartService;

    //添加商品到购物车
    @PostMapping("carts")
    public ResponseData add(@RequestBody AddCartRequest addCartRequest) {
        AddCartResponse addCartResponse = iCartService.addToCart(addCartRequest);
        if (ShoppingRetCode.SUCCESS.getCode().equals(addCartResponse.getCode())) {
            return new ResponseUtil<>().setData("成功");
        }
        return new ResponseUtil<>().setErrorMsg(addCartResponse.getMsg());
    }

    //获得购物车列表
    @GetMapping("carts")
    public ResponseData show(HttpServletRequest request) {
        CartListByIdRequest cartListByIdRequest = new CartListByIdRequest();

        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        long userId = Long.parseLong(userInfo);
        cartListByIdRequest.setUserId(userId);
        CartListByIdResponse cartListByIdResponse = iCartService.getCartListById(cartListByIdRequest);
        if (ShoppingRetCode.SUCCESS.getCode().equals(cartListByIdResponse.getCode())) {
            return new ResponseUtil<>().setData(cartListByIdResponse.getCartProductDtos());
        }
        return new ResponseUtil<>().setErrorMsg(cartListByIdResponse.getMsg());
    }


    //更新购物车中的商品
    @PutMapping("carts")
    public ResponseData update(@RequestBody UpdateCartNumRequest updateCartNumRequest) {
        UpdateCartNumResponse updateCartNumResponse = iCartService.updateCartNum(updateCartNumRequest);
        if (ShoppingRetCode.SUCCESS.getCode().equals(updateCartNumResponse.getCode())) {
            return new ResponseUtil<>().setData("成功");
        }
        return new ResponseUtil<>().setErrorMsg(updateCartNumResponse.getMsg());
    }

    // 全选
    @PutMapping("items")
    public ResponseData selectAll(@RequestBody CheckAllItemRequest checkAllItemRequest){

        CheckAllItemResponse checkAllItemResponse = iCartService.checkAllCartItem(checkAllItemRequest);

        if (ShoppingRetCode.SUCCESS.getCode().equals(checkAllItemResponse.getCode())) {
            return new ResponseUtil<>().setData("成功");
        }
        return new ResponseUtil<>().setErrorMsg(checkAllItemResponse.getMsg());
    }



}
